package com.giornoadd.timex.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.giornoadd.timex.dao.EmployeeManager;
import com.giornoadd.timex.model.Employee;
import com.giornoadd.timex.util.ApplicationSecurityManager;
import com.giornoadd.timex.util.TimexJmxBean;
import com.giornoadd.timex.web.form.SignInForm;

/**
 * Controller for the Sign In screen.
 * @author anil
 */
@Controller
@RequestMapping("/signIn")
public class SignInController
{
	@Autowired
    private EmployeeManager employeeManager;
	@Autowired
    private ApplicationSecurityManager applicationSecurityManager;
	@Autowired
    private TimexJmxBean timexJmxBean;
    
	@RequestMapping(method=RequestMethod.GET)
	public void showForm(@RequestHeader(value="X-Requested-With", required=false) String requestedWith, HttpSession session, Model model) {
		SignInForm signInForm = (SignInForm) session.getAttribute("singInForm");
		model.addAttribute(signInForm != null ? signInForm : new SignInForm());

	}
	
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView onSubmit(@RequestHeader(value="X-Requested-With", required=false) String requestedWith, @Valid SignInForm signInForm, BindingResult result, HttpSession session, Model model)
	{

		if (result.hasErrors()) {
			return null;
		}
		
		Employee employee = employeeManager.getEmployee(signInForm.getEmployeeId());
        if (employee == null) return null;
		
		timexJmxBean.setSignInCount(timexJmxBean.getSignInCount() + 1);
		applicationSecurityManager.setEmployee(session, employee);

		
		return new ModelAndView(new RedirectView("timesheet"));
	}
   
	public EmployeeManager getEmployeeManager()
    {
        return employeeManager;
    }

    public void setEmployeeManager(EmployeeManager employeeManager)
    {
        this.employeeManager = employeeManager;
    }

    public ApplicationSecurityManager getApplicationSecurityManager()
    {
        return applicationSecurityManager;
    }

    public void setApplicationSecurityManager(
            ApplicationSecurityManager applicationSecurityManager)
    {
        this.applicationSecurityManager = applicationSecurityManager;
    }
    
    public TimexJmxBean getTimexJmxBean()
    {
        return timexJmxBean;
    }

    public void setTimexJmxBean(TimexJmxBean timexJmxBean)
    {
        this.timexJmxBean = timexJmxBean;
    }
}
